/*
 * Students:
 * Massimiliano Rango - 610826
 * Martina Benedetto - 610962
 * 
 * A.A 2011/2012
 * 
*/ 

import java.io.FileWriter;
import java.io.PrintWriter;
import java.rmi.Naming;

/**
 *
 * This class represents the RMIServer, which runs concurrently with the application.
 * The RMIServer waits for the results sent by the Client, in order to print them
 * in the GUI and save them in the output.txt file.
 * 
 * @version 1.0 27 Dec 2011
 * @author Martina Benedetto 
 *
 */
public class RMIServer extends Thread {
	
	private static final String HOST = "localhost";
	
	public void run() {
		try {
			Results res = new Results();
			String rmiObjName = "rmi://" + HOST + "/Results";
			Naming.rebind(rmiObjName, res);

			while (true) {
				synchronized(res) {
        				while (res.isEmptyResults())
        					res.wait();
				}
				PrintWriter out = new PrintWriter(new FileWriter("output.txt", true));
				SimResultInterface nextResult = res.popNextResult();
				out.println(nextResult.getProtocol() + " " + nextResult.getNSim() + " " + nextResult.getNNodes() + " " 
						+ nextResult.getRadius() + " " + nextResult.getProb() + " " + nextResult.getG() + " " 
						+ nextResult.getTotEnergy() + " " + nextResult.getSendEnergy() + " " 
						+ nextResult.getRecEnergy() + " " + nextResult.getSigEnergy() + " " + nextResult.getMinSentMess() 
						+ " " + nextResult.getMaxSentMess() + " " + nextResult.getAvgSentMess() + " " 
						+ nextResult.getStdDevSentMess() + " " + nextResult.getMinRecMess() + " " 
						+ nextResult.getMaxRecMess() + " " + nextResult.getAvgRecMess() + " " + nextResult.getStdDevRecMess()
						+ " " + nextResult.getMinSigCheck() + " " + nextResult.getMaxSigCheck() + " " 
						+ nextResult.getAvgSigCheck() + " " + nextResult.getStdDevSigCheck() + " " 
						+ nextResult.getMinConsEnergy() + " " + nextResult.getMaxConsEnergy() + " " 
						+ nextResult.getAvgConsEnergy() + " " + nextResult.getStdDevConsEnergy() + " " 
						+ nextResult.getMinStoredMess() + " " + nextResult.getMaxStoredMess() + " " 
						+ nextResult.getAvgStoredMess() + " " + nextResult.getStdDevStoredMess());
				out.close();
			}
			
		} catch (Exception e) {
			System.out.println(e);
			return;
		}
	}
	
	public static void main (String[] args) {
		RMIServer rmi = new RMIServer();
		rmi.start();
	}
}
